<template>
    <rui-page :defines="defines">
        <Row>
            <rui-query :label-width="120"
                       :query="queryAtomData"
                       :query-rows="queryRows"
                       ref="atomQuery"
            />
        </Row>
        <rui-table :defineId="'voucherAtomConfig'"
                   :fixedLeft="['action','atomKey','atomName']"
                   :showIndex="false"
                   :select="false"
                   :slots="[{key:'action',slot:'action'}]"
                   @loadDatas="queryAtomData"
                   ref="atomTable"
                   ref-query="atomQuery">
            <template slot="toolBar">
                <Button @click="createAtom" icon="ios-add" type="primary" >添加</Button>
            </template>
            <template slot="action" slot-scope="{ row }">
                <div>
                    <Button @click="edit(row)" size="small" type="primary" >编辑</Button>
                    <Button @click="delAtom(row)" size="small" type="error" >删除</Button>
                </div>
            </template>
        </rui-table>
        <Modal
            :closable="false"
            :mask-closable="false"
            :title="atomConfigTitle"
            :width="1000"
            v-model="atomConfig">
            <rui-form :afterChange="editFromChange"
                      :form-options="atomConfigFormOptions"
                      :label-width="120"
                      :read-only="false"
                      ref="editForm">
                <template slot="operatorKey" slot-scope="{ key,item,data,dataDic }">
                    <CheckboxGroup style="width:800px" v-model="data[key]">
                        <Checkbox :label="item.key" :key="item.key" v-for="item in operatorList">
                            <span>{{item.name}}</span>
                        </Checkbox>
                    </CheckboxGroup>
                </template>
            </rui-form>
            <div slot="footer">
                <Button @click="atomConfig = false" size="small">取消</Button>
                <Button @click="checkAtomConfig" size="small" type="primary">保存</Button>
            </div>
        </Modal>
    </rui-page>
</template>

<script>
    import voucherAtomConfig from "../defines/voucher-atom-define";
    import {addAtom, deleteAtom, list, modifyAtom} from "@/projects/basic/api/contract/voucher/voucherAtom"
    import {deepClone} from "@/libs/utils/ObjectClone";
    import RuleConstant from '../voucher-rules/src/component/constant/constant'
    export default {
        name: "voucher-atom",
        data() {
            return {
                defines:[],
                atomConfig: false,
                componentConfig: false,
                modelType: '',
                atomConfigTitle: '凭证原子编辑',
                componentConfigTitle: '原子组件配置',
                validateRules: {},
                requestPath:'contractAccount',
                atomComponentInfo: {
                    atomInfo: {},
                    componentInfo: null
                },
                queryRows: [
                    {
                        defineId: 'voucherAtomConfig',
                        totalSpan: 24,
                        fields: ['atomKey', 'atomName']
                    }
                ],
                atomConfigFormOptions: [
                    {
                        isGroup: false,
                        grids: [
                            {defineId: 'voucherAtomConfig', span: 12, fields: ['atomKey', 'atomOperatorScope']},
                            {defineId: 'voucherAtomConfig', span: 12, fields: ['atomName', 'relList']},
                            {defineId: 'voucherAtomConfig', span: 12, fields: ['atomType']},

                        ]
                    },
                    {
                        isGroup: false,
                        grids: [
                            {defineId: 'voucherAtomConfig', span: 24, fields: [ 'atomValueExpress']},
                        ]
                    },
                    {
                        isGroup: false,
                        hideKey: ['operatorKeyList'],
                        grids: [
                            {
                                defineId: 'voucherAtomConfig',
                                span: 24,
                                fields: ['operatorKeyList'],
                                slots: [{key: 'operatorKeyList', slotName: 'operatorKey'}]
                            },
                        ]
                    }
                ]
            };
        },
        methods: {
            queryAtomData(queryData) {
                list(queryData,this.requestPath).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.atomTable.updateTableData(records, total);
                    }
                });
            },
            createAtom() {
                this.atomConfigTitle = '新建凭证原子';
                this.$refs.editForm.setAllFieldRequired(true);
                this.$refs.editForm.setFieldRequired("atomKey",false);
                this.$refs.editForm.setFieldReadOnly("atomKey",true);
                this.modelType = 'new';
                let self = this;
                this.$nextTick(() => {
                    self.$refs.editForm.resetFrom();
                    this.atomConfig = true;
                })
            },
            delAtom(row) {
                let self = this;
                this.$Modal.confirm({
                    title: "确认",
                    content: `确认删除该原子[${row.atomName}]？`,
                    onOk: () => {
                        deleteAtom(row.id,self.requestPath).then(res => {
                            self.$refs['atomTable'].reloadData();
                        })
                    }
                });
            },

            edit(row) {
                this.atomConfigTitle = '配置' + row.atomName + "(" + row.atomKey + ")";
                this.modelType = 'modify';
                this.$refs.editForm.updateFormData(deepClone(row));
                this.$refs.editForm.setAllFieldRequired(true);
                this.$refs.editForm.setFieldRequired("atomKey",false);
                this.$refs.editForm.setFieldReadOnly("atomKey",true);
                this.atomConfig = true;
            },
            checkAtomConfig() {
                let self = this;
                this.$refs.editForm.getForm().validate((valid) => {
                    if (valid) {
                        let reqData = self.$refs.editForm.getFormData();
                        if (self.modelType === 'new') {
                            reqData.atomComponentConfig = '{}';
                            addAtom(reqData,self.requestPath).then(res => {
                                if (res.code === '0000') {
                                    self.$refs['atomTable'].reloadData();
                                    self.atomConfig = false;
                                } else {
                                    self.$Message.error(res.msg);
                                }
                            }).catch(err => {

                            })
                        } else if (self.modelType === 'modify') {
                            modifyAtom(reqData,self.requestPath).then(res => {
                                if (res.code === '0000') {
                                    self.$refs['atomTable'].reloadData();
                                    self.atomConfig = false;
                                } else {
                                    self.$Message.error(res.msg);
                                }
                            })
                        }
                    } else {
                        self.atomConfig = true;
                        self.$Message.error('数据不完整!');
                    }
                })
            },
            checkAtomComponentConfig() {
                let self = this;
                this.$refs.componentConfigForm.validate((valid) => {
                    if (valid) {
                        self.atomComponentInfo.atomInfo.atomComponentConfig = JSON.stringify(self.atomComponentInfo.componentInfo);
                        modifyAtom(self.atomComponentInfo.atomInfo,self.requestPath).then(res => {
                            if (res.code === '0000') {
                                self.$refs['atomTable'].reloadData();
                                self.componentConfig = false;
                                self.$refs.componentConfigForm.resetFields();
                            } else {
                                self.$Message.error(res.msg);
                            }
                        })
                    } else {
                        self.componentConfig = true;
                        self.$Message.error('数据不完整!');
                    }
                })
            },
            editFromChange(key, afterValue) {
                if (key === 'atomOperatorScope' && afterValue === 'cust') {
                    this.$refs.editForm.setFiledHide('operatorKeyList', false);
                } else if (key === 'atomOperatorScope') {
                    this.$refs.editForm.setFiledHide('operatorKeyList', true);
                    this.$refs.editForm.setFiledValue('operatorKeyList', []);
                }
            },

        },
        computed: {
            operatorList() {
                let operators = [];
                operators.push(...RuleConstant.operators.arithmeticOperator);
                return operators;
            }
        },
        created(){
            if(this.$route.meta.params&&this.$route.meta.params.dicKey&&this.$route.meta.params.dicKey!==''){
                let atomDefine = deepClone(ruleAtomDefine);
                atomDefine[0].dicKey = this.$route.meta.params.dicKey;
                this.defines.push({
                    id: 'voucherAtomConfig',
                    fields: atomDefine
                })
            }else{
                this.defines.push({
                    id: 'voucherAtomConfig',
                    fields: voucherAtomConfig
                })
            }
        },
        mounted() {
            this.$refs['atomTable'].reloadData();
        }
    };
</script>
